#include<iostream>
#include<unistd.h>
#include<pthread.h>

const int num = 5;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
void* Wait(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);

        pthread_cond_wait(&gcond, &mutex);
        usleep(1000);
        std::cout << "I am:" << name << std::endl;
        pthread_mutex_unlock(&mutex);
        //usleep(1000);
        
    }
}
int main()
{
    pthread_t threads[num];
    for(int i = 0; i < num; i++)
    {
        char* name = new char[1024];
        snprintf(name, 1024, "thread-%d", i + 1);
        pthread_create(threads + i, nullptr, Wait, (void*)name);
        usleep(1000);
    }

    sleep(1);
    //主线程唤醒其他线程
    while(true)
    {
        //pthread_cond_signal(&gcond);
        pthread_cond_broadcast(&gcond);
        std::cout << "唤醒一个线程" << std::endl;
        sleep(1);
    }



    for(int i = 0; i < num; i++)
    {
        pthread_join(threads[i], nullptr);
    }
}